package com.mz.mattress.client.service.impl;

import com.mz.mattress.api.entity.*;
import com.mz.mattress.api.enums.OrderStatusEnum;
import com.mz.mattress.api.enums.OrderTagEnum;
import com.mz.mattress.api.util.DateUtil;
import com.mz.mattress.api.util.IdUtil;
import com.mz.mattress.client.mapper.*;
import com.mz.mattress.client.service.OrderDataService;
import com.mz.mattress.client.util.RandomGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Service
public class OrderDataServiceImpl implements OrderDataService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private OrderUseTimesMapper orderUseTimesMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public void genOrderDataByDay(Date date) {

        int total = RandomGenerator.nextTotal();
        int buyCount = RandomGenerator.nextPayTotal();
        int cancelCount = total - buyCount;

        String startDate = DateUtil.toDateTimeStr(date);

        //一次都没购买
        List<Member> member0List = memberMapper.list0(startDate, total);
        Collections.shuffle(member0List);

        //已购买过一次
        List<Member> member1List = memberMapper.list1(startDate, total);
        Collections.shuffle(member1List);

        List<Goods> goodsList = goodsMapper.list();

        HashMap<Integer, Goods> goodsMap = new HashMap<>();
        for (Goods goods : goodsList) {
            goodsMap.put(goods.getId(), goods);
        }

        List<String> dateTimeList = RandomGenerator.generateSortedOrderDate(date, total);

        int member0idx = 0;
        int member1idx = 0;

        for (int i = 0; i < total; i++) {

            int goodsId = RandomGenerator.nextGoodsId();
            Goods goods = goodsMap.get(goodsId);

            //取用户
            Member member = null;
            if (goodsId == 1) {
                if (member0List.size() > member0idx) {
                    member = member0List.get(member0idx);
                    member0idx++;
                } else if (member1List.size() > member1idx) {
                    member = member1List.get(member1idx);
                    member1idx++;
                }
            } else if (member1List.size() < member1idx + 1) {
                //一次的没有了
                member = member0List.get(member0idx);
                member0idx++;
            } else {
                member = member1List.get(member1idx);
                member1idx++;
            }

            if (member == null) {
                log.info("member is null");
                return;
            }

            String dateTime = dateTimeList.get(i);
//            Long orderId = createOrderId(dateTime);
            Long orderId = IdUtil.genOrderId(OrderTagEnum.mattressOrder, dateTime);

            Order order = new Order();
            order.setOrderId(orderId);
            order.setTotalMoney(goods.getPrice());
            order.setMemberId(member.getId());
            order.setMoney(goods.getPrice());
            order.setGoodsId(goodsId);

            if (goodsId == 2) {
                order.setCouponMoney(9000);
                order.setPayMoney(order.getMoney() - order.getCouponMoney());
            }

            order.setTitle(goods.getTitle());
            order.setCount(goods.getCount());
            order.setRemain(goods.getCount());
            order.setMobile(member.getMobile());
            order.setPerMoney(goods.getPerMoney());
            order.setCreateTime(dateTime);

            boolean cancelOrder = RandomGenerator.nextIsCancelOrder();
            if (cancelOrder && cancelCount > 0) {

                order.setStatus(OrderStatusEnum.CANCEL.getValue());
                orderMapper.insert(order);

                cancelCount--;
            } else {

                order.setRemain(goods.getCount() - 1);
                //已消费
                order.setStatus(OrderStatusEnum.HAS_CONSUME.getValue());
                orderMapper.insert(order);

                //标记已消费
                Member update = new Member();
                update.setId(member.getId());
                update.setCount(1);
                memberMapper.updateById(update);

                int deviceId = RandomGenerator.nextDeviceId();
                Device device = deviceMapper.selectById(deviceId);

                String startTime = DateUtil.nextUseTime(dateTime);
                OrderUseTimes record = new OrderUseTimes();
                record.setOrderId(orderId);
                record.setProductKey(device.getProductKey());
                record.setDeviceCode(device.getDeviceCode());
                record.setDeviceId(device.getId());
                record.setMemberId(member.getId());
                record.setSex(member.getSex());
                record.setBirthday(member.getBirthday());
                record.setWeight(member.getWeight());
                record.setMerchantId(device.getMerchantId());
                record.setMerchantName(device.getMerchantName());
                //初始状态 0
                record.setStatus(3);
                record.setMoney(order.getPerMoney());
                record.setCreateTime(startTime);
                orderUseTimesMapper.insert(record);
            }

        }

    }

    @Override
    public void genPaidOrder(String mobile, Integer goodsId, Integer count) {

        Member member = memberMapper.selectByMobile(mobile);
        if (member == null) {
            return;
        }

        Goods goods = goodsMapper.selectById(goodsId);
        if (goods == null) {
            return;
        }

        Integer money = goods.getPrice();

        for (Integer i = 0; i < count; i++) {
            Long orderId = IdUtil.generatedCommonId(OrderTagEnum.mattressOrder);
            Order order = new Order();
            order.setOrderId(orderId);
            order.setTotalMoney(goods.getPrice());
            order.setCouponId(1391);
            order.setMemberId(member.getId());
            order.setMobile(mobile);
            order.setCouponMoney(0);
            order.setMoney(money);
            order.setPayMoney(money);
            order.setGoodsId(goods.getId());
            order.setTitle(goods.getTitle());
            order.setCount(goods.getCount());
            order.setRemain(goods.getCount());
            order.setStatus(OrderStatusEnum.PAID.getValue());
            orderMapper.insert(order);
        }

    }

    private static Long createOrderId(String time) {
        String ss = time.replace(" ", "").replace("-", "").replace(":", "");
        String str = ss.substring(2) + (10 + ThreadLocalRandom.current().nextInt(89));
        return Long.valueOf(str);
    }

    public static void main(String[] args) {

        String s = "2024-10-17 15:20:52";

        System.out.println(createOrderId(s));

    }
}
